package cn.kust.apiuser.service.impl;

import cn.kust.apiuser.remote.ServiceUserCenterClient;
import cn.kust.apiuser.remote.ServiceVerificationcodeClient;
import cn.kust.apiuser.service.VerificationCodeService;
import cn.kust.microtourismcommon.constant.CommonStatusEnum;
import cn.kust.microtourismcommon.constant.IdentityConstants;
import cn.kust.microtourismcommon.constant.TokenConstants;
import cn.kust.microtourismcommon.pojo.dto.MicroTourismUser;
import cn.kust.microtourismcommon.pojo.dto.ResponseResult;
import cn.kust.microtourismcommon.pojo.request.VerificationCodeDTO;
import cn.kust.microtourismcommon.pojo.response.NumberCodeResponse;
import cn.kust.microtourismcommon.pojo.response.TokenResponse;
import cn.kust.microtourismcommon.util.JwtUtils;
import cn.kust.microtourismcommon.util.RedisPrefixUtils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.client.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author WY
 * @data 2022/7/5 11:15
 **/
@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {
    @Autowired
    private ServiceVerificationcodeClient serviceVerificationcodeClient;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;



    public Integer generatorCode(String userPhone) {
        System.out.println("================验证码服务==============");
        System.out.println("================检查当前手机号是否已经存在验证码");
        //        根据手机号尝试从redis读取验证码
        System.out.println("尝试从redis读取" + userPhone + "的验证码");
//        校验验证码
        System.out.println("校验验证码");
        String key = RedisPrefixUtils.generatorCodeKeyByPhone(userPhone);

        String redisCode = stringRedisTemplate.opsForValue().get(key);
        if (redisCode != null){
            System.out.println("已经存在验证码，不再发送短信信息");
            return Integer.valueOf(redisCode);
        }


        System.out.println("调用远程验证码微服务，获取验证码");
        ResponseResult<NumberCodeResponse> numberOfVerificationcode = serviceVerificationcodeClient.getNumberOfVerificationcode(4);
        int numberCode = numberOfVerificationcode.getData().getNumberCode();
        System.out.println("获取成功，验证码为：" + numberCode);
        System.out.println("存入redis");
        key = RedisPrefixUtils.generatorCodeKeyByPhone(userPhone);

        stringRedisTemplate.opsForValue().set(key, numberCode + "", 2, TimeUnit.MINUTES);
        System.out.println("存入成功！");
        //调用第三方短信服务接口


        return numberCode;
    }


    @Autowired
    private ServiceUserCenterClient serviceUserCenterClient;

    /**
     * 校验验证码
     *
     * @param userPhone
     * @param verificationCode
     * @return
     */
    @Override
    public ResponseResult checkCode(String userPhone, String verificationCode) {
//        根据手机号尝试从redis读取验证码
        System.out.println("尝试从redis读取" + userPhone + "的验证码");
//        校验验证码
        System.out.println("校验验证码");
        String key = RedisPrefixUtils.generatorCodeKeyByPhone(userPhone);

        String redisCode = stringRedisTemplate.opsForValue().get(key);
        //验证码是否过期
        System.out.println("redis中的value：" + redisCode);
        if (StringUtils.isBlank(redisCode)) {
            return ResponseResult.fail(CommonStatusEnum.VERIFICATION_CODE_ERROR.getCode(), CommonStatusEnum.VERIFICATION_CODE_ERROR.getValue());
        }

        //验证码是否匹配
        if (verificationCode.equals(redisCode)) {
            System.out.println("用户验证码正确");

        } else {
            System.out.println("验证码错误");
            return ResponseResult.fail(CommonStatusEnum.VERIFICATION_CODE_ERROR.getCode(), CommonStatusEnum.VERIFICATION_CODE_ERROR.getValue());
        }


//        用户中心服务
        System.out.println("登录/注册服务");
        VerificationCodeDTO verificationCodeDTO = new VerificationCodeDTO();
        verificationCodeDTO.setVerificationCode(verificationCode);
        verificationCodeDTO.setUserPhone(userPhone);
        ResponseResult responseResult = serviceUserCenterClient.loginOrRegister(verificationCodeDTO);

        MicroTourismUser microTourismUser = (MicroTourismUser) responseResult.getData();
//        颁发token令牌
        System.out.println("颁发token令牌");
//        String token = JwtUtils.generatorToken(userPhone, IdentityConstant.PASSENGER_IDENTITY);
        //双token
        String accessToken = JwtUtils.generatorToken(userPhone, IdentityConstants.User_IDENTITY,Long.toString(microTourismUser.getId()), TokenConstants.ACCESS_TOKEN_TYPE);
        String refreshToken = JwtUtils.generatorToken(userPhone, IdentityConstants.User_IDENTITY,Long.toString(microTourismUser.getId()),TokenConstants.REFRESH_TOKEN_TYPE);

        //token存入redis中
        String accessTokenKey = RedisPrefixUtils.generatorTokenKey(userPhone, IdentityConstants.User_IDENTITY,TokenConstants.ACCESS_TOKEN_TYPE);
        String refreshTokenKey = RedisPrefixUtils.generatorTokenKey(userPhone, IdentityConstants.User_IDENTITY,TokenConstants.REFRESH_TOKEN_TYPE);
        //使用redis存储token有效期，有效期以后token不自带
//        stringRedisTemplate.opsForValue().set(accessTokenKey, accessToken, 30, TimeUnit.DAYS);
        stringRedisTemplate.opsForValue().set(accessTokenKey, accessToken, 20, TimeUnit.MINUTES);

//        stringRedisTemplate.opsForValue().set(refreshTokenKey, refreshToken, 31, TimeUnit.DAYS);
        stringRedisTemplate.opsForValue().set(refreshTokenKey, refreshToken, 160, TimeUnit.MINUTES);

        TokenResponse tokenResponse = new TokenResponse();
        tokenResponse.setAccessToken(accessToken);
        tokenResponse.setRefreshToken(refreshToken);

        return ResponseResult.success(tokenResponse);
    }


}
